package com.tkm.expressions.eg

//  实际开发中，可以使用idea自动生成equals和hashCode
class Person(val name: String, val age: Int) {
    override fun equals(other: Any?): Boolean {
        //  引用相等，则为同一对象
        if (this === other) return true
        //  类型不匹配，则返回false
        val other = (other as? Person) ?: return false
        //  判定内容是否相等
        return age == other.age && name == other.name
    }

    override fun hashCode(): Int {
        var result = age
        result = 31 * result + name.hashCode()
        return result
    }
}

fun main() {
    //  Set、Map的key，被要求唯一，根据hashCode判断
    val personSet = HashSet<Person>()
    val personList = ArrayList<Person>()
    repeat(10) {
        val p = Person("Bread", 24)
        personSet.add(p)
        personList.add(p)
    }
    println(personSet.size)
    println(personList.size)

    val p1 = Person("Bread", 24)
    val p2 = Person("TKM", 19)
    val p3 = Person("TKM", 19)

    //  ==：使用equals方法判断
    println(p1 == p2)
    println(p1 == p3)
    println(p2 == p3)
}
